using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DIS_App_Client.MainManagers
{
	#region using
	using DIS_App_Client.Helpers;
	using System.Data;
	using System.Drawing;
	using System.IO;
	using DIS_App_Client.DIS_WS_BusinessLayer;
	#endregion
	public partial class FrmViewWeeklyReport : Form
	{
		private System.Windows.Forms.TextBox txtIDChemistWareHouse;

        public FrmViewWeeklyReport(bool enableChon = false)
		{
			InitializeComponent();
		}

		public void LoadDetailInfo(WeeklyReportDTO item)
		{
			txtIDChemistWareHouse.Text = item.IDChemistWareHouse == -1 ? "" : item.IDChemistWareHouse.ToString();
			dtStartDate.Value = item.StartDate;
            dtEndDate.Value = item.EndDate;
		}

		private void InitGridView()
		{
            DataGridViewTextBoxColumn objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "ID",
                DataPropertyName = "ID",
                Name = "ID",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6))
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Date",
                DataPropertyName = "Date",
                Name = "Date",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6))
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "IsVerified",
                DataPropertyName = "IsVerified",
                Name = "IsVerified",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6))
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "IsShipped",
                DataPropertyName = "IsShipped",
                Name = "IsShipped",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6))
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "IsPaid",
                DataPropertyName = "IsPaid",
                Name = "IsPaid",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6)) - 1
            };
            dtgvData.Columns.Add(objColumn);
            objColumn = new DataGridViewTextBoxColumn
            {
                HeaderText = "Total",
                DataPropertyName = "Total",
                Name = "Total",
                Width = (int)((dtgvData.Width - dtgvData.RowHeadersWidth) * ((double)1 / 6)) - 1
            };
            dtgvData.Columns.Add(objColumn);
		}

		public void InitHiddenFields()
		{
			txtIDChemistWareHouse = new System.Windows.Forms.TextBox
			{
				Name = "txtIDChemistWareHouse",
				Text = ""
			};
			txtIDChemistWareHouse.Visible = false;
		}

        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnSelectChemistWareHouse_Click(object sender, EventArgs e)
        {
            FrmManageChemistWareHouse frm = new FrmManageChemistWareHouse(true);
            frm.Handler += GetChemistWareHouse;
            frm.ShowDialog();
        }

        public void GetChemistWareHouse(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });
            txtIDChemistWareHouse.Text = comp[0];
            txtChemistWareHouse.Text = comp[1];
        }

        private void btnViewReport_Click(object sender, EventArgs e)
        {
            var errorText = "";
			if (!ValidateInput(ref errorText))
			{
				MessageBox.Show(errorText, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}

            var report = BusService.Instance.WeeklyReport_SelectByIDChemistWareHouseAndReportDate(int.Parse(txtIDChemistWareHouse.Text), dtStartDate.Value, dtEndDate.Value);

            if (report != null)
            {
                txtNote.Text = report.Note;

                var lstDate = CommonHelper.GetDateRange(dtStartDate.Value, dtEndDate.Value);
                var lstItem = new List<OrdersDTO>();

                foreach (var date in lstDate)
                {
                    var lstOrders = BusService.Instance.Orders_SelectByIDChemistWareHouseAndOrderDate(int.Parse(txtIDChemistWareHouse.Text), date);
                    foreach (var order in lstOrders)
                    {
                        lstItem.Add(order);
                    }
                }

                var dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("Date");
                dt.Columns.Add("IsVerified");
                dt.Columns.Add("IsShipped");
                dt.Columns.Add("IsPaid");
                dt.Columns.Add("Total");
                var income = 0.0;
                for (int i = 0; i < lstItem.Count; i++)
                {
                    var lstOrderDetails = lstItem[i].OrderDetails;
                    var sum = 0.0;
                    foreach (var detail in lstOrderDetails)
                    {
                        var money = detail.Quantity * detail.Price;
                        var remain = money - money * (detail.Discount / 100);
                        sum += remain;
                    }
                    income += sum;
                    dt.Rows.Add(lstItem[i].ID, lstItem[i].OrderDate.ToShortDateString(), lstItem[i].IsVerified == true ? "Yes" : "No", lstItem[i].IsShipped == true ? "Yes" : "No", lstItem[i].IsPaid == true ? "Yes" : "No", sum);
                }
                dt.Rows.Add("", "", "", "", "SUM", income);
                DataView objTimeSheetDV = new System.Data.DataView(dt);
                objTimeSheetDV.AllowNew = false;
                dtgvData.AutoGenerateColumns = false;
                dtgvData.DataSource = objTimeSheetDV;
                dtgvData.ClearSelection();
            }
        }

        private bool ValidateInput(ref string errorText)
        {
            if (txtIDChemistWareHouse.Text == string.Empty)
            {
                errorText = "Please select ChemistWareHouse";
                return false;
            }
            if (dtStartDate.Value == DateTime.MinValue)
            {
                errorText = "Please select start date";
                return false;
            }
            if (dtStartDate.Value.DayOfWeek != DayOfWeek.Monday)
            {
                errorText = "Start date must be monday";
                return false;
            }
            if (dtEndDate.Value == DateTime.MinValue)
            {
                errorText = "Please select end date";
                return false;
            }
            if (dtEndDate.Value.DayOfWeek != DayOfWeek.Sunday)
            {
                errorText = "End date must be sunday";
                return false;
            }
            if (dtStartDate.Value > dtEndDate.Value)
            {
                errorText = "Start date larger than end date";
                return false;
            }

            var lstDate = CommonHelper.GetDateRange(dtStartDate.Value, dtEndDate.Value);

            if (lstDate.Count > 7)
            {
                errorText = "Start date and end date is not same in a week";
                return false;
            }
            var report = BusService.Instance.WeeklyReport_SelectByIDChemistWareHouseAndReportDate(int.Parse(txtIDChemistWareHouse.Text), dtStartDate.Value, dtEndDate.Value);
            if (report == null)
            {
                errorText = "There is no any reports created in this range of date";
                return false;
            }

            var numOrders = 0;
            foreach (var date in lstDate)
            {
                var lstItem = BusService.Instance.Orders_SelectByIDChemistWareHouseAndOrderDate(int.Parse(txtIDChemistWareHouse.Text), date);
                numOrders += lstItem.Length;
                if (numOrders > 0)
                {
                    return true;
                }
            }

            if (numOrders == 0)
            {
                errorText = "Range of date does not have any orders";
                return false;
            }
            return true;
        }

        private void dtgvData_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvData.SelectedRows.Count > 0 && dtgvData.SelectedRows[0].Cells[4].Value.ToString().ToUpper() != "SUM")
            {
                FrmDetailOfOrder frm = new FrmDetailOfOrder(int.Parse(dtgvData.SelectedRows[0].Cells["ID"].Value.ToString()));
                frm.ShowDialog();
            }
        }

        private void FrmViewWeeklyReport_Load(object sender, EventArgs e)
        {
            InitGridView();
            InitHiddenFields();
        }

        private void dtgvData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dtgvData.Rows[e.RowIndex].Cells[4].Value.ToString().ToUpper() == "SUM")
            {
                e.CellStyle.BackColor = Color.Crimson;
                e.CellStyle.ForeColor = Color.White;
            }
        }
	}
}